package com.road.vast.springboot.controller;

import com.road.vast.springboot.utils.SecurityUtil;
import org.activiti.api.process.model.ProcessInstance;
import org.activiti.api.process.model.builders.ProcessPayloadBuilder;
import org.activiti.api.process.runtime.ProcessRuntime;
import org.activiti.api.runtime.shared.query.Page;
import org.activiti.api.runtime.shared.query.Pageable;
import org.activiti.api.task.model.Task;
import org.activiti.api.task.model.builders.TaskPayloadBuilder;
import org.activiti.api.task.runtime.TaskRuntime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Author 郭泽鹏
 * @Date 2020/6/29 9:10
 * @Version 1.0
 * @Description activiti前端控制器
 */
@RestController
@RequestMapping("/activiti")
public class ActivitiController {
    @Autowired
    private ProcessRuntime processRuntime;
    @Autowired
    private TaskRuntime taskRuntime;
    @Autowired
    private SecurityUtil securityUtil;

    @GetMapping("/start-instance")
    public String startInstance(){
        ProcessInstance processInstance = processRuntime.start(
                ProcessPayloadBuilder
                        .start()
                        .withProcessDefinitionKey("pro-holiday")
                        .build());          //启动流程实例

        System.out.println("流程实例ID号：" + processInstance.getId());
        System.out.println("流程实例名：" + processInstance.getName());
        return "启动流程实例成功，\tID号：" + processInstance.getId() + "\t流程实例名：" + processInstance.getName();
    }

    @GetMapping("/task-process")
    public String taskProcess(){

        Page<Task> tasks = taskRuntime.tasks(Pageable.of(0, 10));   //分页查询

        if (tasks.getTotalItems() > 0){     //是否有任务
            for (Task task : tasks.getContent()) {      //遍历任务列表
                System.out.println("任务信息：" + task);

                String taskId = task.getId();       //任务id

                taskRuntime.claim(TaskPayloadBuilder.claim().withTaskId(taskId).build());     //拾取任务

                taskRuntime.complete(TaskPayloadBuilder.complete().withTaskId(taskId).build());     //执行任务
                System.out.println("任务ID号：" + taskId + "\t任务名：" + task.getName() + "\t执行完成");
                return "任务ID号：" + taskId + "\t任务名：" + task.getName() + "\t执行完成";
            }
        }
        return "没有可执行的任务";
    }

}
